//
//  DBManager.swift
//  jiahui
//
//  Created by 3tee on 2024/12/20.
//

import Foundation
import WCDB.Swift

struct DBPath {
    static  let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/DB/chatDB"
}


class DBManager: NSObject {
    //创建一个单列
    static let shared = DBManager()
    var db: Database!
    override init() {
        //根据路径初始化db
         db = Database(at: DBPath.path)
        print("初始化了db path  = \(DBPath.path)")
    }
   
    //创建一个表
    func createTab() {
        do {
            try db.create(table: "Message", of: MessageModel.self)
        } catch let err  {
            print(err.localizedDescription)
        }
    }

    func insert<T: TableEncodable>(objs:[T], tableName: String) {
        do {
            try db.insertOrIgnore(objs, intoTable: tableName)
        } catch let error  {
            if let error = error as? WCDBError {
                print("插入数据失败 \(error.description)")
            }
        }
    }
    
    func getMsgs<T: TableDecodable>(cls: T.Type) -> [T]?{
        do {
            let list: [T] = try db.getObjects(fromTable: "Message")
            return list
        } catch let err {
            print("查询数据失败")
        }
        return nil
    }
    
}

